package com.example.chatapp.manager;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;
import java.util.Set;

/**
 * Redis缓存操作管理器
 * 职责：封装所有Redis缓存相关操作，避免Service直接操作RedisTemplate
 */
@Component
public class RedisCacheManager {
    
    private final RedisTemplate<String, Object> redisTemplate;
    private final String onlinePrefix;
    private final String recentPrefix;
    private final String seqPrefix;
    
    public RedisCacheManager(RedisTemplate<String, Object> redisTemplate,
                             @Value("${app.redis.online-prefix}") String onlinePrefix,
                             @Value("${app.redis.recent-messages-key-prefix}") String recentPrefix,
                             @Value("${app.redis.seq-key-prefix}") String seqPrefix) {
        this.redisTemplate = redisTemplate;
        this.onlinePrefix = onlinePrefix;
        this.recentPrefix = recentPrefix;
        this.seqPrefix = seqPrefix;
    }
    
    // ===== 在线状态管理 =====
    
    /**
     * 设置用户在线状态
     */
    public void setUserOnline(String username, String roomId, Duration ttl) {
        String key = onlinePrefix + username;
        redisTemplate.opsForValue().set(key, roomId, ttl);
        System.out.println("[RedisCacheManager] Set user online: " + username + " in room: " + roomId);
    }
    
    /**
     * 移除用户在线状态
     */
    public void removeUserOnline(String username) {
        String key = onlinePrefix + username;
        redisTemplate.delete(key);
        System.out.println("[RedisCacheManager] Removed user online: " + username);
    }
    
    /**
     * 获取用户所在房间
     */
    public String getUserRoom(String username) {
        String key = onlinePrefix + username;
        Object value = redisTemplate.opsForValue().get(key);
        return value != null ? value.toString() : null;
    }
    
    /**
     * 获取指定房间的所有在线用户
     */
    public List<String> getOnlineUsersInRoom(String roomId) {
        Set<String> allKeys = redisTemplate.keys(onlinePrefix + "*");
        List<String> usersInRoom = new java.util.ArrayList<>();
        
        if (allKeys != null && !allKeys.isEmpty()) {
            for (String key : allKeys) {
                Object value = redisTemplate.opsForValue().get(key);
                if (value != null && roomId.equals(value.toString())) {
                    // 提取用户名（移除前缀）
                    String username = key.substring(onlinePrefix.length());
                    usersInRoom.add(username);
                }
            }
        }
        
        System.out.println("[RedisCacheManager] Found " + usersInRoom.size() + " online users in room: " + roomId);
        return usersInRoom;
    }
    
    // ===== 最近消息缓存 =====
    
    /**
     * 推送最近消息到列表
     */
    public void pushRecentMessage(String roomId, String messageJson) {
        String key = recentPrefix + roomId;
        redisTemplate.opsForList().leftPush(key, messageJson);
        redisTemplate.opsForList().trim(key, 0, 99); // 保留最新100条
    }
    
    /**
     * 获取最近消息列表
     */
    public List<Object> getRecentMessages(String roomId, int limit) {
        String key = recentPrefix + roomId;
        return redisTemplate.opsForList().range(key, 0, limit - 1);
    }
    
    /**
     * 清理房间的最近消息
     */
    public void clearRecentMessages(String roomId) {
        String key = recentPrefix + roomId;
        redisTemplate.delete(key);
    }
    
    // ===== 序列号管理 =====
    
    /**
     * 获取下一个序列号（原子递增）
     */
    public long getNextSeq(String roomId) {
        String key = seqPrefix + roomId;
        Long seq = redisTemplate.opsForValue().increment(key, 1L);
        return seq != null ? seq : 1L;
    }
    
    /**
     * 获取当前序列号
     */
    public Long getCurrentSeq(String roomId) {
        String key = seqPrefix + roomId;
        Object value = redisTemplate.opsForValue().get(key);
        return value != null ? Long.parseLong(value.toString()) : null;
    }
    
    /**
     * 清理房间序列号
     */
    public void clearSeq(String roomId) {
        String key = seqPrefix + roomId;
        redisTemplate.delete(key);
    }
    
    // ===== 通用操作 =====
    
    /**
     * 删除指定key
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }
    
    /**
     * 批量删除
     */
    public Long delete(Set<String> keys) {
        return redisTemplate.delete(keys);
    }
    
    /**
     * 检查key是否存在
     */
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }
    
    /**
     * 获取匹配的所有key
     */
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }
}
